<template>
  <div class="user-management-container">
    <a-card class="section-card">
      <div class="table-toolbar">
        <div class="left">
          <a-input-search
            v-model:value="searchParams.searchText"
            placeholder="搜索用户名/姓名/邮箱"
            style="width: 250px"
            @search="handleSearch"
          />
          <a-select
            v-model:value="searchParams.userRole"
            placeholder="角色筛选"
            style="width: 150px; margin-left: 16px"
            allowClear
            @change="handleSearch"
          >
            <a-select-option value="admin">管理员</a-select-option>
            <a-select-option value="teacher">教师</a-select-option>
            <a-select-option value="student">学生</a-select-option>
          </a-select>
          <a-select
            v-model:value="searchParams.status"
            placeholder="状态筛选"
            style="width: 150px; margin-left: 16px"
            allowClear
            @change="handleSearch"
          >
            <a-select-option :value="1">正常</a-select-option>
            <a-select-option :value="2">禁用</a-select-option>
          </a-select>
        </div>
        <div class="right">
          <a-button type="primary" @click="showAddModal"> <user-add-outlined /> 添加用户 </a-button>
          <a-button
            style="margin-left: 8px"
            @click="handleBatchDelete"
            :disabled="selectedRowKeys.length === 0"
          >
            <delete-outlined /> 批量删除
          </a-button>
          <a-button style="margin-left: 8px" @click="handleSearch">
            <reload-outlined /> 刷新
          </a-button>
        </div>
      </div>

      <a-table
        :columns="columns"
        :data-source="dataList"
        :pagination="pagination"
        :loading="loading"
        :row-selection="{ selectedRowKeys, onChange: onSelectChange }"
        @change="handleTableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'id'">
            <span>{{ record.id }}</span>
          </template>

          <template v-if="column.key === 'userAvatar'">
            <a-avatar :src="record.userAvatar">
              {{ record?.userName.charAt(0).toUpperCase() }}
            </a-avatar>
          </template>

          <template v-if="column.key === 'userRole'">
            <a-tag :color="getRoleColor(record.userRole)">
              {{ getRoleText(record.userRole) }}
            </a-tag>
          </template>

          <template v-if="column.key === 'status'">
            <a-badge
              :status="record.status === 1 ? 'success' : 'default'"
              :text="record.status === 1 ? '正常' : '禁用'"
            />
          </template>
          <template v-else-if="column.dataIndex === 'createTime'">
            {{ dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss') }}
          </template>
          <template v-if="column.key === 'action'">
            <a-space>
              <a @click="() => handleEdit(record)">编辑</a>
              <a-divider type="vertical" />
              <a-dropdown>
                <a class="ant-dropdown-link" @click.prevent> 更多 <down-outlined /> </a>
                <template #overlay>
                  <a-menu>
                    <a-menu-item key="reset-password" @click="() => handleResetPassword(record)">
                      重置密码
                    </a-menu-item>
                    <a-menu-item key="toggle-status" @click="() => handleToggleStatus(record)">
                      {{ record.status === 1 ? '禁用账户' : '启用账户' }}
                    </a-menu-item>
                    <a-menu-item key="delete" @click="() => handleDelete(record)">
                      删除
                    </a-menu-item>
                  </a-menu>
                </template>
              </a-dropdown>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 添加/编辑用户模态框 -->
    <a-modal
      v-model:open="userModalVisible"
      :title="isEditing ? '编辑用户' : '添加用户'"
      @ok="handleUserModalOk"
      @cancel="handleUserModalCancel"
      width="600px"
    >
      <a-form :model="userForm" :rules="userFormRules" ref="userFormRef" layout="vertical">
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item name="userAccount" label="账号">
              <a-input
                v-model:value="userForm.userAccount"
                placeholder="请输入账号"
                :disabled="isEditing"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item name="userName" label="用户名">
              <a-input v-model:value="userForm.userName" placeholder="请输入用户名" />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item name="email" label="邮箱">
              <a-input v-model:value="userForm.email" placeholder="请输入邮箱" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item name="phone" label="电话">
              <a-input v-model:value="userForm.phone" placeholder="请输入电话" />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item name="userRole" label="角色">
              <a-select v-model:value="userForm.userRole" placeholder="请选择角色">
                <a-select-option value="admin">管理员</a-select-option>
                <a-select-option value="teacher">教师</a-select-option>
                <a-select-option value="student">学生</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item name="status" label="状态">
              <a-select v-model:value="userForm.status" placeholder="请选择状态">
                <a-select-option value="active">正常</a-select-option>
                <a-select-option value="inactive">禁用</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>

        <a-form-item v-if="!isEditing" name="userPassword" label="密码">
          <a-input-password v-model:value="userForm.userPassword" placeholder="请输入密码" />
        </a-form-item>

        <a-form-item name="userProfile" label="备注">
          <a-textarea v-model:value="userForm.userProfile" :rows="4" placeholder="请输入备注信息" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import {
  UserAddOutlined,
  DeleteOutlined,
  ReloadOutlined,
  DownOutlined,
} from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import {
  deleteUser,
  getUserVoById,
  listUserVoByPage,
  updateUser,
  userAdd,
} from '@/api/userController'
import dayjs from 'dayjs'
// 表格列定义
const columns = [
  {
    title: '#',
    key: 'id',
    width: 60,
  },
  {
    title: '头像',
    key: 'userAvatar',
    width: 80,
  },
  {
    title: '账号',
    dataIndex: 'userAccount',
    key: 'userAccount',
  },
  {
    title: '用户名',
    dataIndex: 'userName',
    key: 'userName',
    sorter: true,
  },
  {
    title: '邮箱',
    dataIndex: 'email',
    key: 'email',
  },
  {
    title: '角色',
    key: 'userRole',
    dataIndex: 'userRole',
    filters: [
      { text: '管理员', value: 'admin' },
      { text: '教师', value: 'teacher' },
      { text: '学生', value: 'student' },
    ],
    width: 100,
  },
  {
    title: '状态',
    key: 'status',
    dataIndex: 'status',
    filters: [
      { text: '正常', value: 1 },
      { text: '禁用', value: 1 },
    ],
    width: 100,
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    sorter: true,
    width: 170,
  },
  {
    title: '操作',
    key: 'action',
    width: 150,
  },
]
const searchParams = reactive<API.UserQueryDTO>({
  current: 1,
  pageSize: 10,
})
const total = ref(0)
const dataList = ref<API.UserVO[]>([])
const fetchData = async () => {
  const res = await listUserVoByPage({
    ...searchParams,
  })
  if (res.data.data && res.data.code === 0) {
    dataList.value = res.data.data.records ?? []
    total.value = res.data.data.total ?? 0
  } else {
    message.error('获取数据失败' + res.data.msg)
  }
}
onMounted(() => {
  fetchData()
})

// 表格加载状态
const loading = ref(false)

// 分页配置
const pagination = computed(() => {
  return {
    current: searchParams.current ?? 1, //有则按照传过来的，否则默认为1
    pageSize: searchParams.pageSize ?? 10, //默认为 10
    total: Number(total.value) ?? 0, //默认为 0
    showSizeChanger: true,
    showTotal: (total) => `共${total}条数据`,
  }
})

// 选中的行
const selectedRowKeys = ref<string[]>([])

// 用户表单相关
const userFormRef = ref(null)
const userModalVisible = ref(false)
const isEditing = ref(false)
const userForm = reactive<API.UserAddDTO>({
  id:"",
  userName: '',
  userAccount: '',
  email: '',
  phone: '',
  userRole: 'student',
  status: 1,
  userPassword: '',
  userProfile: '',
})

// 表单验证规则
const userFormRules = {
  userName: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度为3-20个字符', trigger: 'blur' },
  ],
  userAccount: [{ required: true, message: '请输入账号', trigger: 'blur' }],
  email: [
    { required: false, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入有效的邮箱地址', trigger: 'blur' },
  ],
  role: [{ required: true, message: '请选择角色', trigger: 'change' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6个字符', trigger: 'blur' },
  ],
}

// 表格选择变更
const onSelectChange = (keys: string[]) => {
  selectedRowKeys.value = keys
}

// 处理表格变更（排序、筛选等）
const handleTableChange = (page: any, filters: any, sorter: any) => {
  loading.value = true
  // 更新分页
  searchParams.current = page.current
  searchParams.pageSize = page.pageSize
  fetchData()
  loading.value = false
}

// 搜索
const handleSearch = (value: string) => {
  loading.value = true
  fetchData()
  loading.value = false
  pagination.value.current = 1
}

// 获取角色文本
const getRoleText = (role: string) => {
  switch (role) {
    case 'admin':
      return '管理员'
    case 'teacher':
      return '教师'
    case 'student':
      return '学生'
    default:
      return '未知'
  }
}

// 获取角色颜色
const getRoleColor = (role: string) => {
  switch (role) {
    case 'admin':
      return 'red'
    case 'teacher':
      return 'blue'
    case 'student':
      return 'green'
    default:
      return 'default'
  }
}
// 显示添加模态框
const showAddModal = () => {
  isEditing.value = false
  userModalVisible.value = true
}

// 处理编辑
const handleEdit = async (record: any) => {
  isEditing.value = true
  //获取原来的数据
  try {
    const res = await getUserVoById({
      id: record.id,
    })
    const userVO = ref<API.UserVO>()
    if (res.data.data && res.data.code === 0) {
      userVO.value = res.data.data
      //拷贝属性至userForm
      // 只拷同名属性
      Object.keys(userForm).forEach(k => {
        if (k in userVO.value) userForm[k] = userVO.value[k];
      });

    } else {
      message.error('获取用户数据失败')
    }
  } catch (e) {
    message.error('获取用户数据失败')
  }
  userModalVisible.value = true
}

// 处理用户模态框确认
const handleUserModalOk = async () => {
  try {
    let res = null
    if (!isEditing.value) {
      //不是编辑，即add
      res = await userAdd({
        ...userForm,
      })
    } else {
      res = await updateUser({
        ...userForm,
      })
    }
    if (res.data.data && res.data.code === 0) {
      await fetchData()
      message.success(isEditing.value ? '用户更新成功' : '用户添加成功')
    } else {
      message.error(isEditing.value ? '用户更新失败' : '用户添加失败')
    }
  } catch (e) {
    message.error(isEditing.value ? '用户更新失败' : '用户添加失败')
  }
  userModalVisible.value = false
}

// 处理用户模态框取消
const handleUserModalCancel = () => {
  userModalVisible.value = false
}

// 处理重置密码
const handleResetPassword = async (record: any) => {
  try {
    const res = await updateUser({
      id: record.id,
      userPassword: '12345678',
    })
    if (res.data.data && res.data.code === 0) {
      message.success(`已重置用户 ${record.userName} 的密码`)
    } else {
      message.error(`重置用户 ${record.userName} 的密码失败`)
    }
  } catch (e) {
    message.error(`重置用户 ${record.userName} 的密码失败`)
  }
}

// 处理切换状态
const handleToggleStatus = async (record: any) => {
  const newStatus = record.status === 1 ? 2 : 1
  console.log(newStatus)
  try {
    const res = await updateUser({
      id: record.id,
      status: newStatus,
    })
    if (res.data.data && res.data.code === 0) {
      await fetchData()
      message.success(`已${newStatus === 1 ? '启用' : '禁用'}用户 ${record.userName}`)
    } else {
      message.error(`${newStatus === 1 ? '启用' : '禁用'}用户 ${record.userName}失败`)
    }
  } catch (e) {
    message.error(`已${newStatus === 1 ? '启用' : '禁用'}用户 ${record.userName}失败`)
  }
}

// 处理删除
const handleDelete = async (record: any) => {
  try {
    const res = await deleteUser({
      id: record.id,
    })
    if (res.data.data && res.data.code === 0) {
      await fetchData()
      message.success(`已删除用户 ${record.userName}`)
    } else {
      message.error(`删除用户 ${record.userName}失败`)
    }
  } catch (e) {
    message.error(`删除用户 ${record.userName}失败`)
  }
}

// 处理批量删除 TODO
const handleBatchDelete = () => {
  if (selectedRowKeys.value.length === 0) return
  console.log(selectedRowKeys.value)
  // 实际项目中这里会调用API批量删除用户
  message.success(`已删除 ${selectedRowKeys.value.length} 个用户`)
  selectedRowKeys.value = []
}
</script>

<style scoped>
.user-management-container {
  padding-bottom: 40px;
  padding-top: 20px;
}

.page-title {
  font-size: 24px;
  margin-bottom: 24px;
  color: var(--primary-color);
}

.section-card {
  margin-bottom: 24px;
  border-radius: 8px;
}

.table-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.left,
.right {
  display: flex;
  align-items: center;
}
</style>
